<script lang="ts" setup>
  import { toRefs, watch, ref, toRaw, nextTick } from 'vue';

  const props = withDefaults(
    defineProps<{
      treeData: any[];
      selected: number[] | object;
      visible: boolean;
      loading: boolean;
      title: string;
    }>(),
    {
      treeData: [] as any,
      selected: [] as any,
      visible: false,
      loading: false,
      title: '',
    },
  );

  const emits = defineEmits(['cancel', 'success']);

  const { treeData, visible, title, selected } = toRefs(props);
  const treeRef = ref();
  watch(selected, (nv: Array<number>) => {
    if (nv) {
      nextTick(() => {
        treeRef.value.setCheckedNodes(toRaw(nv).map((e) => ({ value: e })));
      });
    }
  });

  const onClose = () => {
    emits('cancel');
  };
  const onSubmit = () => {
    let result = treeRef.value.getCheckedNodes(true, false).map((e) => toRaw(e).value);
    emits('success', result);
  };
</script>

<template>
  <el-drawer v-model="visible" :title="title" :width="450" @close="onClose">
    <el-tree v-loading="loading" ref="treeRef" node-key="value" show-checkbox :data="treeData" />
    <template #footer>
      <el-button style="margin-right: 8px" @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
    </template>
  </el-drawer>
</template>

<style lang="less"></style>
